import json
import os
import sys
import threading
import time

import Program
import subprocess
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
#print(Program.File.ReadConfigFile("/etc/ssh/sshd_config")["X11Forwarding"])
#print()
programPath = os.path.split(os.path.realpath(__file__))[0]  # 返回 string
class Window:
    class State:
        def __init__(self, a):
            self.types = a.types
            self.userName = a.userName
            self.password = a.password

        def Install(self):
            messagebox = QMessageBox()
            messagebox.addButton("安装SSH服务端", QMessageBox.YesRole)
            messagebox.addButton("安装RDP服务端", QMessageBox.ActionRole)
            messagebox.addButton("取消", QMessageBox.ActionRole)
            id = messagebox.exec_()
            if id == 2:
                return
            if id == 0:
                Program.Program.RunCommandOnTerminal('''sudo apt install openssh-server''')
                return
            Program.Program.RunCommandOnTerminal('''sudo apt install xrdp''')

    def GetDesktop(self):
        while True:
            for i in range(10 * 1):
                if not self.connectState:
                    break
                time.sleep(0.1)
            os.system("sshpass -p \"{}\" ssh -X \"{}@{}\" python3 /tmp/getdesktop.py".format(self.password.text().strip(), self.userName.text().strip(), self.ip.text().strip()))
            lists = []
            print(subprocess.getoutput("sshpass -p \"{}\" ssh -X \"{}@{}\" python3 /tmp/getdesktop.py".format(self.password.text().strip(), self.userName.text().strip(), self.ip.text().strip())))
            print("sshpass -p \"{}\" ssh -X \"{}@{}\" python3 /tmp/getdesktop.py".format(self.password.text().strip(), self.userName.text().strip(), self.ip.text().strip()))
            self.appInformation = json.loads(subprocess.getoutput("sshpass -p \"{}\" ssh -X \"{}@{}\" python3 /tmp/getdesktop.py".format(self.password.text().strip(), self.userName.text().strip(), self.ip.text().strip())))
            for i in self.appInformation:
                lists.append(i[0])

            self.listmodel.setStringList(lists)



    def __init__(self):
        self.connectState = False

    def AppList_DoubleClicked(self, index):
        print(self.appInformation[index.row()])

        threading.Thread(target=os.system, args=["sshpass -p \"{}\" ssh -X \"{}@{}\" {}".format(self.password.text().strip(), self.userName.text().strip(), self.ip.text().strip(), self.appInformation[index.row()][1])]).start()

    def ConnectButton_Clicked(self):
        ip = self.ip.text().strip()
        user = self.userName.text().strip()
        password = self.password.text()
        if ip == "":
            QMessageBox.critical(widget, "错误", "您未输入IP地址！！！")
            return
        commandHead = ["sshpass ", "qterminal -e ", "qterminal -e ", "padsp rdesktop "]
        command = commandHead[self.types.currentIndex()]
        if self.types.currentIndex() == 3:
            if user != "":
                command = command + "-u \"" + user + "\" "
            if password != "":
                command = command + "-p \"" + password + "\" "
            command = command + ip + " "
            for i in json.loads(Program.File.ReadTxt(Program.File.GetHome() + "/.willow-connect/RDPShare.json")):
                if not i[0]:
                    continue
                command = command + " -r \"disk:{}={}\" ".format(os.path.basename(i[2]), i[2])

        if self.types.currentIndex() == 2 or self.types.currentIndex() == 1:
            if user == "":
                QMessageBox.critical(widget, "错误", "您未输入用户名！！！")
                return
            if password != "":
                command = command + "sshpass -p \"" + password + "\" "
            command = command + "ssh {} \"{}@{}\"".format(["", "-X"][int(self.types.currentIndex() == 1)], user, ip)
        if self.types.currentIndex() == 0:
            if user == "" or password == "":
                QMessageBox.critical(widget, "错误", "未输入用户名或密码")
                return
            print("sshpass -p \"{}\" scp '{}/getdesktop.py' \"{}@{}:/tmp\"".format(password, programPath, user, ip))

            if not os.system("sshpass -p \"{}\" scp '{}/getdesktop.py' \"{}@{}:/tmp\"".format(password, programPath, user, ip)) == 0:
                QMessageBox.critical(widget, "错误", "信息获取错误！")
                return
            print(subprocess.getoutput("sshpass -p \"{}\" ssh -X \"{}@{}\" python3 /tmp/getdesktop.py".format(password, user, ip)))
            appInformation = json.loads(subprocess.getoutput("sshpass -p \"{}\" ssh -X \"{}@{}\" python3 /tmp/getdesktop.py".format(password, user, ip)))
            print(appInformation)
            appList = []
            for i in appInformation:
                appList.append(i[0])
            print(appList)
            listmodel = QStringListModel()
            listmodel.setStringList(appList)
            self.appList.setModel(listmodel)
            self.listmodel = listmodel
            self.appInformation = appInformation
            #self.appList = appList
            self.connectState = True
            Window.ChangeMainFrame()
            threading.Thread(target=Window.GetDesktop).start()
            return
        print(command)
        os.system(command)


    def Types_Clicked(self):
        #print(self.types.currentIndex())
        if self.types.currentIndex() == 3:
            self.userName.setPlaceholderText("需要登录的用户名（选填）")
            self.password.setPlaceholderText("需要登录的密码（选填）")
            return
        if self.types.currentIndex() == 1 or self.types.currentIndex() == 2:
            self.userName.setPlaceholderText("需要登录的用户名（必填）")
            self.password.setPlaceholderText("需要登录的密码（选填）")
            return
        if self.types.currentIndex() == 0:
            self.userName.setPlaceholderText("需要登录的用户名（必填）")
            self.password.setPlaceholderText("需要登录的密码（必填）")
            return

    def ChangeMainFrame(self):
        self.mainFrame.setCurrentIndex([0, 3][int(self.connectState)])


    def LeftFrame(self):
        # 左侧栏
        leftFrame = QFrame(widget)
        leftFrame.setMinimumSize(100, 100)
        leftFrame.setStyleSheet("border-image: url('left.png');")
        leftFrameLayout = QVBoxLayout(leftFrame)
        leftFrame.setLayout(leftFrameLayout)
        mainWindowLayout.addWidget(leftFrame)
        mainFrameButton = QPushButton(leftFrame)
        mainFrameButton.setText("连接")
        mainFrameButton.clicked.connect(Window.ChangeMainFrame)
        mainFrameButton.show()
        settingFrameButton = QPushButton(leftFrame)
        settingFrameButton.setText("设置")
        settingFrameButton.clicked.connect(lambda: self.mainFrame.setCurrentIndex(1))
        settingFrameButton.show()
        aboutFrameButton = QPushButton(leftFrame)
        aboutFrameButton.setText("关于")
        aboutFrameButton.clicked.connect(lambda: self.mainFrame.setCurrentIndex(2))
        aboutFrameButton.show()
        leftFrameLayout.addWidget(mainFrameButton)
        leftFrameLayout.addWidget(settingFrameButton)
        leftFrameLayout.addWidget(aboutFrameButton)
        #leftFrameLayout.addWidget()

    def ExitConnect_Clicked(self):
        self.connectState = False
        self.password.setText("")
        Window.ChangeMainFrame()

    def AddList_Clicked(self):
        #self.shareListValue.setItem()
        #self.rdpShareList = []
        if not os.path.exists(self.sharePath.text().strip()) and self.shareFileButton.isChecked():
            QMessageBox.critical(None, "错误", "路径不合法！")
            return
        self.rdpShareList.append([self.shareStateButton.isChecked(), ["文件", "端口"][int(not self.shareFileButton.isChecked())], self.sharePath.text().strip()])
        self.shareListValue.setItem(len(self.rdpShareList) - 1, 0, QStandardItem(str(self.shareStateButton.isChecked())))
        self.shareListValue.setItem(len(self.rdpShareList) - 1, 1, QStandardItem(["文件", "端口"][int(not self.shareFileButton.isChecked())]))
        self.shareListValue.setItem(len(self.rdpShareList) - 1, 2, QStandardItem(str(self.sharePath.text().strip())))
        
        self.messagebox.close()
        #print()
        Program.File.WriteTxt(Program.File.GetHome() + "/.willow-connect/RDPShare.json", json.dumps(self.rdpShareList))

    def AddList(self):
        print("a")
        messagebox = QDialog()
        self.messagebox = messagebox
        messageboxLayout = QGridLayout()
        messagebox.setWindowModality(Qt.NonModal)
        messagebox.setWindowFlags(Qt.Window)
        messagebox.setWindowModality(Qt.WindowModal)
        messagebox.setWindowModality(Qt.ApplicationModal)
        messagebox.setLayout(messageboxLayout)
        shareFileButton = QRadioButton(messagebox, text="共享文件")
        self.shareFileButton = shareFileButton
        shareFileButton.clicked.connect(lambda: brower.setEnabled(shareFileButton.isChecked()))
        shareFileButton.setChecked(True)
        messageboxLayout.addWidget(shareFileButton, 0, 0)
        shareCOMButton = QRadioButton(messagebox, text="共享端口")
        shareCOMButton.clicked.connect(lambda: brower.setEnabled(shareFileButton.isChecked()))
        messageboxLayout.addWidget(shareCOMButton, 0, 1)

        shareStateButton = QCheckBox(messagebox, text="启用该共享")
        self.shareStateButton = shareStateButton
        shareStateButton.setChecked(True)
        messageboxLayout.addWidget(shareStateButton, 0, 2)
        sharePath = QLineEdit(messagebox)
        messageboxLayout.addWidget(sharePath, 1, 0, 1, 2)
        self.sharePath = sharePath
        sharePath.setPlaceholderText("输入需要共享的文件路径或端口")
        brower = QPushButton(messagebox, text="浏览")
        print(QFileDialog.getSaveFileName(None, ""))
        #brower.clicked.connect(lambda: self.sharePath.setText(QFileDialog.getSaveFileName(None, "", "")[0]))
        brower.clicked.connect(lambda: self.sharePath.setText(QFileDialog.getExistingDirectory(None, "选择要共享的目录", Program.File.GetHome(), QFileDialog.DontUseNativeDialog)))
        messageboxLayout.addWidget(brower, 1, 2)
        brower.show()
        ok = QPushButton(messagebox, text="确定")
        ok.clicked.connect(Window.AddList_Clicked)
        messageboxLayout.addWidget(ok, 2, 2)
        cancel = QPushButton(messagebox, text="取消")
        cancel.clicked.connect(messagebox.close)
        messageboxLayout.addWidget(cancel, 2, 1)
        messagebox.show()
        messagebox.exec_()

    def MainFrame(self):
        #mainFrame = QFrame(widget)
        mainFrame = QTabWidget(widget)
        self.mainFrame = mainFrame
        mainFrame.tabBar().hide()
        mainWindowLayout.addWidget(mainFrame)
        ##########
        # 连接
        ##########
        connectFrame = QWidget()
        connectFrameLayout = QGridLayout(connectFrame)
        connectFrame.setLayout(connectFrameLayout)
        mainFrame.addTab(connectFrame, "连接")
        types = QComboBox(connectFrame)
        types.addItems(["图形界面的ssh", "终端使用带图形界面的ssh", "普通ssh连接", "rdp连接"])
        #state = Window.State(self)
        types.currentIndexChanged.connect(Window.Types_Clicked)
        ip = QLineEdit(connectFrame)
        ip.setPlaceholderText("要连接的IP地址")
        connectButton = QPushButton(connectFrame, text="连接")
        connectButton.clicked.connect(Window.ConnectButton_Clicked)
        userName = QLineEdit(connectFrame)
        userName.setPlaceholderText("需要登录的用户名（必填）")
        password = QLineEdit(connectFrame)
        password.setPlaceholderText("需要登录的密码（必填）")
        password.setEchoMode(QLineEdit.Password)

        connectFrameLayout.addWidget(types, 0, 0)
        connectFrameLayout.addWidget(ip, 0, 1)
        connectFrameLayout.addWidget(connectButton, 0, 2)
        connectFrameLayout.addWidget(userName, 1, 0, 1, 3)
        connectFrameLayout.addWidget(password, 2, 0, 1, 3)
        #connectFrame.show()
        self.types = types
        self.userName = userName
        self.password = password
        self.ip = ip
        ##########
        # 高级设置
        ##########
        settingFrame = QWidget()
        mainFrame.addTab(settingFrame, "高级设置")
        settingFrameLayout = QGridLayout(settingFrame)
        settingFrame.setLayout(settingFrameLayout)
        #settingFrameLayout.addWidget(settingFrame)
        settingFrame.setStyleSheet('''QCheckBox::indicator::unchecked {
                image: url("closecheck.png");
            }
            QCheckBox::indicator::checked {
                image: url("opencheck.png");
            }
            QCheckBox::indicator { 
    	        width: 26px;
    	        height: 50px;
            }''')
        serverSetting = QGroupBox(settingFrame)
        serverSetting.setTitle("服务器设置")
        settingFrameLayout.addWidget(serverSetting)
        serverSettingLayout = QGridLayout(serverSetting)
        sshServer = QCheckBox(serverSetting)
        sshServer.setEnabled(not Program.Program.CheckSshService())
        sshServer.setChecked(Program.Program.IsSshServerOpen_X11Setting())
        rdpServer = QCheckBox(serverSetting)
        sshServer.setText("运行 SSH 服务器")
        serverSettingLayout.addWidget(sshServer)
        rdpServer.setText("运行 RDP 服务器")
        serverSettingLayout.addWidget(rdpServer)
        sshServer.show()
        rdpServer.show()
        serverSetting.show()
        rdpConnectSetting = QGroupBox()
        rdpConnectSetting.setTitle("RDP（rdesktop）连接设置")
        rdpConnectSettingLayout = QVBoxLayout()
        rdpConnectSetting.setLayout(rdpConnectSettingLayout)
        settingFrameLayout.addWidget(rdpConnectSetting)
        localSound = QCheckBox(settingFrame, text="本地播放远程音频")
        rdpConnectSettingLayout.addWidget(localSound)
        localSound.show()
        shareCOM = QCheckBox(settingFrame, text="共享本地文件/端口")
        rdpConnectSettingLayout.addWidget(shareCOM)
        shareCOM.show()
        shareCOMSetting = QPushButton(rdpConnectSetting, text="更多设置")
        shareCOMSetting.clicked.connect(lambda: self.mainFrame.setCurrentIndex(4))
        rdpConnectSettingLayout.addWidget(shareCOMSetting)
        shareCOMSetting.show()
        rdpConnectSetting.show()
        ##########
        # 关于
        ##########
        aboutFrame = QWidget()
        aboutFrameLayout = QGridLayout(aboutFrame)
        mainFrame.addTab(aboutFrame, "关于")
        aboutFrame.setLayout(aboutFrameLayout)
        aboutLabel = QLabel(aboutFrame)
        aboutFrameLayout.addWidget(aboutLabel)
        aboutQt = QPushButton(aboutFrame)
        aboutQt.clicked.connect(lambda: QMessageBox.aboutQt(widget, "关于Qt"))
        aboutFrameLayout.addWidget(aboutQt)
        aboutQt.setText("关于Qt")
        aboutQt.show()

        aboutLabel.setText("<p align='center'>杨柳连接</p><p align='center'>版本：1.0.0</p>")
        aboutLabel.show()
        ##################
        # ssh 图形界面连接
        ##################
        connectFrame = QWidget()
        mainFrame.addTab(connectFrame, "ssh 图形连接")
        connectFrameLayout = QGridLayout()
        connectFrame.setLayout(connectFrameLayout)
        appList = QListView(connectFrame)
        appList.setEditTriggers(QListView.NoEditTriggers)
        appList.setSelectionMode(QListView.SingleSelection)
        appList.doubleClicked.connect(Window.AppList_DoubleClicked)
        connectFrameLayout.addWidget(appList, 0, 0, 2, 1)
        programLineEdit = QLineEdit(connectFrame)
        self.programLineEdit = programLineEdit
        programLineEdit.setPlaceholderText("输入要运行的程序（支持带参数）")
        connectFrameLayout.addWidget(programLineEdit, 0, 1)
        programLineEdit.show()
        programRunButton = QPushButton(connectFrame)
        connectFrameLayout.addWidget(programRunButton, 0, 2)
        programRunButton.setText("运行")
        programRunButton.clicked.connect(lambda: threading.Thread(target=os.system, args=["sshpass -p \"{}\" ssh -X \"{}@{}\" {}".format(self.password.text().strip(), self.userName.text().strip(), self.ip.text().strip(), self.programLineEdit.text())]).start())
        programRunButton.show()
        exitConnect = QPushButton(connectFrame)
        connectFrameLayout.addWidget(exitConnect, 1, 1, 1, 2)
        exitConnect.setText("退出连接")
        exitConnect.clicked.connect(Window.ExitConnect_Clicked)
        exitConnect.show()
        appList.show()
        self.appList = appList
        #################
        # rdp 共享文件设置
        #################
        rdpShareFrame = QWidget()
        rdpShareFrameLayout = QGridLayout()
        rdpShareFrame.setLayout(rdpShareFrameLayout)
        mainFrame.addTab(rdpShareFrame, "rdp共享设置")
        addButton = QPushButton(rdpShareFrame, text="添加")
        addButton.clicked.connect(Window.AddList)
        rdpShareFrameLayout.addWidget(addButton, 0, 0, 1, 1)
        addButton.show()
        editButton = QPushButton(rdpShareFrame, text="编辑")
        rdpShareFrameLayout.addWidget(editButton, 0, 1, 1, 1)
        editButton.show()
        delButton = QPushButton(rdpShareFrame, text="删除")
        rdpShareFrameLayout.addWidget(delButton, 0, 2, 1, 1)
        delButton.show()
        shareList = QTableView(rdpShareFrame)
        shareList.setEditTriggers(QTableView.NoEditTriggers)
        shareList.setSelectionBehavior(QTableView.SelectRows)
        shareList.setSelectionMode(QTableView.SingleSelection)
        rdpShareFrameLayout.addWidget(shareList, 1, 0, 1, 4)
        shareListValue = QStandardItemModel()
        self.shareListValue = shareListValue
        shareListValue.setHorizontalHeaderItem(2, QStandardItem("路径"))
        shareListValue.setHorizontalHeaderItem(1, QStandardItem("模式"))
        shareListValue.setHorizontalHeaderItem(0, QStandardItem("状态"))
        head = 0
        if not os.path.exists(Program.File.GetHome() + "/.willow-connect"):
            os.mkdir(Program.File.GetHome() + "/.willow-connect")
        if not os.path.exists(Program.File.GetHome() + "/.willow-connect/RDPShare.json"):
            Program.File.WriteTxt(Program.File.GetHome() + "/.willow-connect/RDPShare.json", json.dumps([]))
            pass
        self.rdpShareList = json.loads(Program.File.ReadTxt(Program.File.GetHome() + "/.willow-connect/RDPShare.json"))#[["True", "文件", "/home/gfdgd_xi"]]
        for i in self.rdpShareList:
            shareListValue.setItem(head, 0, QStandardItem(str(i[0])))
            shareListValue.setItem(head, 1, QStandardItem(i[1]))
            shareListValue.setItem(head, 2, QStandardItem(i[2]))
            head = head + 1
        shareList.setModel(shareListValue)
        shareList.horizontalHeader().setStretchLastSection(True)
        shareList.show()
        #mainFrame.setCurrentIndex(4)
        ##########
        # 显示
        ##########
        mainFrame.show()

def Test():
    # 主面板
    mainFrame = QFrame(widget)
    settingFrame = QFrame(mainFrame)
    settingFrame.setStyleSheet('''QCheckBox::indicator::unchecked {
                image: url("closecheck.png");
            }
            QCheckBox::indicator::checked {
                image: url("opencheck.png");
            }
            QCheckBox::indicator { 
    	        width: 26px;
    	        height: 50px;
            }''')
    mainFrameLayout = QGridLayout(mainFrame)
    settingFrame.setLayout(mainFrameLayout)
    mainWindowLayout.addWidget(mainFrame)
    # 创建控件
    sshChoose = QCheckBox(mainFrame, text="SSH服务器状态")
    rdpChoose = QCheckBox(mainFrame, text="RDP服务器状态")
    sshChoose.setEnabled(not Program.Program.CheckSshService())
    sshChoose.setChecked(Program.Program.IsSshServerOpen_X11Setting())
    # rdpChoose.setChecked(Program.Program.IsSshServerOpen_X11Setting())
    # installSsh = QPushButton(mainFrame, text="安装/卸载SSH服务器")
    # installRdp = QPushButton(mainFrame, text="安装/卸载RDP服务器")
    installNeedProgram = QPushButton(mainFrame, text="安装依赖程序")
    installNeedProgram.clicked.connect(Window.State.Install)
    # 显示窗口
    mainFrameLayout.addWidget(sshChoose, 1, 0)
    mainFrameLayout.addWidget(rdpChoose, 1, 1)
    mainFrameLayout.addWidget(installNeedProgram, 0, 1)
    # mainFrameLayout.addWidget(installRdp, 1, 1)
    sshChoose.show()
    rdpChoose.show()
    installNeedProgram.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 主窗口
    widget = QWidget()
    widget.setWindowTitle("杨柳连接")
    mainWindowLayout = QHBoxLayout(widget)
    widget.setLayout(mainWindowLayout)
    Window = Window()
    Window.LeftFrame()
    Window.MainFrame()


    widget.show()
    sys.exit(app.exec_())